package com.qth.valet.common.listener;


import com.qth.valet.common.netty.WebSocketServerHandler;
import com.qth.valet.common.utils.ResponseResult;
import com.qth.valet.entity.po.Driver;
import com.qth.valet.entity.po.Orders;
import com.qth.valet.service.DriversService;
import com.qth.valet.service.OrdersService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

// 订单监听器
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderListener {
    private final OrdersService ordersService;

    private final DriversService driversService;

    private final WebSocketServerHandler webSocketServerHandler;

    // 监听订单创建事件，@Async表示异步处理
    @Async
    @EventListener
    public void handleOrderCreatedEvent(OrderCreatedEvent event)  {
        Orders newOrder = event.getOrder();
        log.info("监听到新订单创建：" + newOrder.getId());
        Driver driver = ordersService.selectDriver(newOrder);
        if (driver != null) {
            ResponseResult responseResult = ordersService.grabOrder(driver.getId(), newOrder.getId());
            if (responseResult.getStatus()) {
                log.info("派送订单" + newOrder.getId() + "给司机:" + driver.getId());
                webSocketServerHandler.sendMsg(driver.getId(), newOrder.getId());
                driversService.removeDriverAddr(driver.getId());
            }
        }
    }

}

